import React, { Component } from 'react';
import propTypes from 'prop-types';
import { Link } from 'react-router-dom';
import Form from '@wanhu/antd-legacy/lib/form';
// import Input from '@wanhu/antd-legacy/lib/input';
import { Icon, Input, message } from 'antd';
import { diseaseList, diseaseInfo, func } from '@wanhu/business/lib/health-record/prop-types';
// import ChronicDiseaseTable from './chronic-diseases-table';
// 个人疾病
import ChoseSlowSickTable from './chose-slow-sick-table'
// import FamilyDiseasesTable from './family-diseases-table';
// 家族疾病
import FamilyChoseSlowSickTable from './family-chose-slow-sick-table'
// 系统消息
import SystemMessage from './system-message'
// 当前用药
import UseMedicationComponent from './use-medication-component'
// import { toastErrorCaptureThrows } from '../../../../../Toast';
import api from '../../../../../../api/api';
import './index.less';
const { TextArea } = Input;
const FormItem = Form.Item;

const autosizeConfig = { minRows: 2 };

// 防抖 先立即执行，再等2秒
// const debounce=(fn, wait=1000)=> {
//   let timer = null;
//   return function () {
//       let context = this
//       let args = arguments
//       if (timer) {
//           clearTimeout(timer);
//           timer = null;
//       }
//       timer = setTimeout(function () {
//           fn.apply(context, args)
//       }, wait)
//   }
// }
const debounce = function (fn, wait = 1000) {
    let time = null;
    return function () {
        const self = this
        if (time) {
            clearTimeout(time);
            time = null;
        }
        time = setTimeout(function () {
            console.log('thisthis', self);
            fn.apply(this);
        },wait)
    }
}
export default class DiseaseInfoEdit extends Component {
    static propTypes = {
        patientId: propTypes.string.isRequired,
        diseaseList: diseaseList.isRequired,
        diseaseInfo: diseaseInfo.isRequired,
        setDiseaseInfo: func.isRequired,
    }

    state = {
        userMedicationDemand: [],
        getId: '',
        slowSickData: [],
        allergies: '',
        diseaseMessage: {},
        allergiesEdit: true,
        allergiesSaveLoading:false
    }

    // @toastErrorCaptureThrows
    async componentDidMount() {
        const { patientId } = this.props;
        const userMedicationDemand = await api.getUserMedicationDemand(patientId);
        this.setState({ userMedicationDemand });
        // this.fun()
        // rebuild start
        this.getSlowSickData()
    }
    // fun=async()=>{
    //     const { setDiseaseInfo,diseaseInfo } = this.props;
    //     let a = ''

    //     let setObkj = setDiseaseInfo
    //     if(diseaseInfo.allergies.value){
    //         a = diseaseInfo.allergies.value || '无'
    //         a = a.trim()
    //         setDiseaseInfo({
    //             allergies: a?a+' ':'无',
    //         });
    //     }else{
    //         setDiseaseInfo({
    //             allergies: '无',
    //         });
    //     }

    // }
    setAllergies = (evt) => {
        const { setDiseaseInfo } = this.props;
        let value = evt.target.value
        setDiseaseInfo({
            allergies: value,
        });
    }
    setAllergiesBlur = (evt) => {
        const { setDiseaseInfo } = this.props;
        let value = evt.target?evt.target.value:'无'
        setDiseaseInfo({
            allergies: value?value:'无',
        });
    }
    setPastMedicalHistoryBlur = (evt) => {
        const { setDiseaseInfo } = this.props;
        let value = evt.target?evt.target.value:'无'
        setDiseaseInfo({
            pastMedicalHistory: value?value:'无',
        });
    }

    setPastMedicalHistory = (evt) => {
        const { setDiseaseInfo } = this.props;
        setDiseaseInfo({
            pastMedicalHistory: evt.target.value,
        });
    }

    setChronicDiseases =async (data) => {
        const { setDiseaseInfo } = this.props;
        setDiseaseInfo({
            chronicDiseases: data,
        });
        // allergy: 无4
        // pastMedicalHistory: 2
        // chronicDiseases: [{"diseaseId":"61a8c39ec86f4dd386afe4efabfe69db"}]
        // homeMedicalHistories: []
    }
    setFamilyDiseases = (data) => {
        const { setDiseaseInfo } = this.props;
        setDiseaseInfo({
            familyDiseases: data,
        });
    }

    // 新的方法，下一步重构使用
    getSlowSickData = async () => {
        const { patientId } = this.props;
        const data = await api.getPatientDiseaseInfo(patientId);
        console.log('datadatadata', data);
        this.setState({
            allergies: data.allergies,
            diseaseMessage:data
        })
    }
    textareaChange = (evt) => {
        this.setState({
            allergies:evt.target.value
        })
    }
    allergiesSave = debounce(async () => {
        const { patientId } = this.props;
        const { diseaseMessage, allergies } = this.state;
        const diseData = {
            chronicDiseases: [],
            homeMedicalHistories: [],
            pastMedicalHistory: diseaseMessage.pastMedicalHistory,
            allergies:allergies
        }
        try {
            this.setState({
                allergiesSaveLoading:true
            })
            await api.updateDiseaseInfo(patientId, diseData);
            message.success('保存成功')
            this.setState({
                allergiesEdit: true,
                allergiesSaveLoading:false
            })
        }
        catch (e) {
            this.setState({
                allergiesSaveLoading:false
            })
            message.error(e.message?e.message:'过敏史保存失败，请刷新后重试');
        }
    },300)
    render() {
        const pathname = window.location.pathname;
        const search = window.location.search;
        // 跳到用药需求 MedicationDemand
        // const url = pathname.replace('/CreateHealthRecords','/MedicationDemand') + search;
        // 跳到规律用药 RegularMedication
        const url = pathname.replace('/CreateHealthRecords','/RegularMedication') + search;
        const { patientId, diseaseList, diseaseInfo } = this.props;
        const { userMedicationDemand } = this.state;
        const chronicDiseases = diseaseInfo.chronicDiseases.value;
        const familyDiseases = diseaseInfo.familyDiseases.value;
        let userMedicationDemandView;
        if (userMedicationDemand && userMedicationDemand.length) {
            userMedicationDemandView = userMedicationDemand.map(d => (
                <li key={d.drugRequirementId}>
                    {d.commonName}
                    {d.productName ? `（${d.productName}）` : null}
                </li>
            ));
        } else {
            userMedicationDemandView = (
                <li className="no-drug-demand">
                    暂无当前用药信息
                </li>
            );
        }
        return (
            <div className="disease-info-edit">
                <FormItem
                    colon={false}
                    label="诊疗情况"
                >
                    {/* <ul className="drug-demand">
                        { userMedicationDemandView }
                    </ul> */}
                    <UseMedicationComponent patientId={ patientId }></UseMedicationComponent>
                    <div className="drug-demand-link">
                        <Icon type="exclamation-circle" theme="outlined" />
                        用药内容请在
                        <Link to={url}>
                        【<span style={{color: 'red'}}>规律用药</span>】
                        </Link>
                        模块中添加
                    </div>
                </FormItem>
                <FormItem
                    colon={false}
                    label="慢病情况"
                    className="no-validator"
                >
                    <ChoseSlowSickTable value={this.state.slowSickData} patientId={ patientId}></ChoseSlowSickTable>
                    {/* 老组件，新上后记得删除相关代码，要不忒乱 */}
                    {/* <ChronicDiseaseTable
                        diseaseList={diseaseList}
                        value={chronicDiseases}
                        onChange={this.setChronicDiseases}
                    /> */}
                </FormItem>
                {/* <FormItem
                    colon={false}
                    label="既往史"
                    validateStatus={diseaseInfo.pastMedicalHistory.validateStatus}
                    help={diseaseInfo.pastMedicalHistory.help}
                >
                    <Input.TextArea
                        value={diseaseInfo.pastMedicalHistory.value}
                        onChange={this.setPastMedicalHistory}
                        onBlur={this.setPastMedicalHistoryBlur}
                        ref={(input)=>{this.textinput=input}}
                        autosize={autosizeConfig}
                        maxLength={200}
                    />
                </FormItem> */}
                <FormItem
                    colon={false}
                    label="家族病史"
                >
                    <FamilyChoseSlowSickTable value={this.state.slowSickData} patientId={ patientId}></FamilyChoseSlowSickTable>
                    {/* 老组件，新上后记得删除相关代码，要不忒乱 */}
                    {/* <FamilyDiseasesTable
                        diseaseList={diseaseList}
                        value={familyDiseases}
                        onChange={this.setFamilyDiseases}
                    /> */}
                </FormItem>
                <FormItem
                    colon={false}
                    label="过敏史"
                    validateStatus={diseaseInfo.pastMedicalHistory.validateStatus}
                    help={diseaseInfo.pastMedicalHistory.help}
                >
                    <div className="marginR120 test">
                        <TextArea value={this.state.allergies} rows={2} onChange={(evt) => this.textareaChange(evt)} maxLength={200} placeholder="输入其他过敏药物或者过敏食物" readonly={this.state.allergiesEdit ? 'readonly' : false} className={ this.state.allergiesEdit?"noEdit":null }/>
                        <div className="allergiesRow">
                            {this.state.allergiesEdit ? <span className="allergiesSaveBtn" onClick={() => { this.setState({allergiesEdit:false})}}>编辑</span>
                                : <span className="allergiesSaveBtn" onClick={() => this.allergiesSave()}>{ this.state.allergiesSaveLoading?<Icon type="loading" />:null} 保存</span>}
                        </div>
                    </div>
                    {/* <Input.TextArea
                        value={diseaseInfo.allergies.value}
                        onChange={this.setAllergies}
                        onBlur={this.setAllergiesBlur}
                        autosize={autosizeConfig}
                        maxLength={200}
                        placeholder="输入其他过敏药物或者过敏食物"
                    /> */}
                </FormItem>
                <FormItem
                    colon={false}
                    label="系统信息"
                >
                    <SystemMessage patientId={ patientId }></SystemMessage>
                </FormItem>
            </div>
        );
    }
}
